using System;
using System.Collections.Generic;
using NetworkIndexer.CoreExtensions.ServiceLocation;
using StructureMap;

namespace Minion.Web.Main.DependencyResolution
{
    public static class IoC
    {
        public static IContainer Initialize()
        {
            ObjectFactory.Initialize(x => x.Scan(scan =>
                {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                    var privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
                    if (!string.IsNullOrEmpty(privateBinPath))
                    {
                        var strArray = privateBinPath.Split(new[] {';'});
                        foreach (var str2 in strArray)
                        {
                            scan.AssembliesFromPath(str2);
                        }
                    }
                    else
                    {
                        scan.AssembliesFromPath(AppDomain.CurrentDomain.BaseDirectory);
                    }
                }));
            var serviceLocatorConfigurations = ObjectFactory.GetAllInstances<IServiceLocatorConfiguration>();
            Configure(config => ApplyServiceLocationConfigurations(serviceLocatorConfigurations, config));
            return ObjectFactory.Container;
        }

        private static void ApplyServiceLocationConfigurations(
            IEnumerable<IServiceLocatorConfiguration> serviceLocatorConfigurations, ConfigurationExpression config)
        {
            foreach (var configuration in serviceLocatorConfigurations)
            {
                configuration.Configure(config);
            }
        }

        private static void Configure(Action<ConfigurationExpression> configure)
        {
            ObjectFactory.Configure(configure);
        }
    }
}